//login.js
//获取应用实例
var app = getApp();
Page({
  data: {
    remind: '加载中',
    angle: 0,
    userInfo: {},
    regFlag: true // 是否展示授权按钮
  },
  goToIndex:function(){
    wx.switchTab({
      url: '/pages/food/index',
    });
  },
  onLoad:function(){
    wx.setNavigationBarTitle({
      title: app.globalData.shopName
    })
    this.checkLogin()
  },
  onShow:function(){

  },
  onReady: function(){
    var that = this;
    setTimeout(function(){
      that.setData({
        remind: ''
      });
    }, 1000);
    wx.onAccelerometerChange(function(res) {
      var angle = -(res.x*30).toFixed(1);
      if(angle>14){ angle=14; }
      else if(angle<-14){ angle=-14; }
      if(that.data.angle !== angle){
        that.setData({
          angle: angle
        });
      }
    });
  },
  // 判断用户是否已经登录
  checkLogin: function () {
    let that = this
    wx.login({
      success: function (res) {
        wx.request({
          url: app.buildUrl('/check-reg'),
          method: 'POST',
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          data: {
            code: res.code
          },
          success: function (res) {
            console.log('判断用户是否已经登录')
            console.log(res)
            if (res.data.code != 200) {
              that.setData({
                regFlag: false 
              })
              return
            }
            app.setCache('token', res.data.data.token)
            that.goToIndex()
          }
        })
      }
    })
  },
  // 用户登录方法
  login: function (e) {
    let that = this

    if ( !e.detail.userInfo ) {
      app.alert({
        content: '授权失败，请再次点击'
      })
      return
    }

    let data = e.detail.userInfo

    wx.login({
      success: function (res) {
        if (!res.code) {
          app.alert({
            content: '授权失败，请再次点击'
          })
          return
        }
        data['code'] = res.code
        wx.request({
          url: app.buildUrl('/login'),
          method: 'POST',
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          data,
          success: function (res) {
            console.log('login请求发送成功')
            if (res.data.code != 200) {
              app.alert({'content': res.data.msg})
              return
            }
            app.setCache('token', res.data.data.token)
            that.goToIndex()
          }
        })
      }
    })
  }
});